//
//  CZEmoticoInputView.swift
//  007-表情键盘
//
//  Created by 名品导购网MPLife.com on 2017/12/15.
//  Copyright © 2017年 sweet. All rights reserved.
//

import UIKit
//可重用标识符
private let cellId = "cellId"
/// 表情输入视图
class CZEmoticoInputView: UIView {
    
    
    @IBOutlet var pageControl: UIPageControl!
    @IBOutlet var toolBar: CZEmoticonToolBar!
    @IBOutlet var collectionView: UICollectionView!
    //选中表情回调闭包
    private var selectedEmoticonCallBack:((_ emticon:CZEmoticon?)->())?
    /// 加载并且返回输入视图
    ///
    /// - Returns: <#return value description#>
    class func inputView(selectedEmticon:@escaping (_ emticon:CZEmoticon?)->())->CZEmoticoInputView {
        let nib = UINib(nibName: "CZEmoticoInputView", bundle: nil)
        let v = nib.instantiate(withOwner: nib, options:nil)[0] as! CZEmoticoInputView
        //记录闭包
        v.selectedEmoticonCallBack = selectedEmticon
        return v
    }
    override func awakeFromNib() {
        //注册可重用cell
        let nib = UINib(nibName: "CZEmoticonCell", bundle: nil)
        collectionView.register(nib, forCellWithReuseIdentifier: cellId)
        //设置工具栏代理
        toolBar.delegate = self
        
        //设置分页控件的图片
        //important point
        
        let bundle = CZEmoticonManager.shared.bundle
        guard let normalImage = UIImage(named: "compose_keyboard_dot_normal", in: bundle, compatibleWith: nil),let selectImage = UIImage(named: "compose_keyboard_dot_selected", in: bundle, compatibleWith: nil) else {
            return
        }
        //使用填充图片设置颜色
        //        pageControl.pageIndicatorTintColor = UIColor(patternImage: normalImage)
        //        pageControl.currentPageIndicatorTintColor = UIColor(patternImage: selectImage)
        //设置私有成员变量
        pageControl .setValue(normalImage, forKey: "_pageImage")
        pageControl.setValue(selectImage, forKey: "_currentPageImage")
    }
    
}
extension CZEmoticoInputView:CZEmoticonToolBarDlegate{
    func emoticonToolBarDidSelectedItemIndex(toolBar: CZEmoticonToolBar, index: Int) {
        //让collectionview 发生滚动  滚动到每一个分组的低0页
        let indexPath = IndexPath(item: 0, section: index)
        collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
        //设置分组按钮的选中状态
        toolBar.selectedIndex = index
        
    }
}
extension CZEmoticoInputView:UICollectionViewDelegate{
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //获取中心点
        var  center = scrollView.center
        center.x += scrollView.contentOffset.x
        //2.获取当前显示的cell的indexpath
        let paths = collectionView.indexPathsForVisibleItems
        //判断中心点在哪一个indexpath上 在哪一个页面上
        var targetIndexPath: IndexPath?
        
        for indexpath in paths {
            //1.根据indexpath获得cell
            let cell = collectionView.cellForItem(at: indexpath)
            //判断中心点位置
            if (cell?.frame.contains(center))! {
                targetIndexPath = indexpath
                break
            }
        }
        
        guard  let target = targetIndexPath else {
            return
        }
         //判断是否找到目标的indexpath
        //indexpath.section  对应的就是分组
        toolBar.selectedIndex = target.section
        //设置分页控件
        //总页数 不同的分组 页数不一样
        pageControl.numberOfPages = collectionView.numberOfItems(inSection: target.section)
        pageControl.currentPage = target.item

    }
}
extension CZEmoticoInputView:UICollectionViewDataSource{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return CZEmoticonManager.shared.packages.count
    }
    //每个分租的表情包中 表情页面的数量 emoticons.count/20
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //返回每个分组中表情页的数量
        return CZEmoticonManager.shared.packages[section].numberOfPages
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        //1.取cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CZEmoticonCell
        //2 设置cell
            cell.emoticons = CZEmoticonManager.shared.packages[indexPath.section].emoticon(page: indexPath.item)
        cell.delegate  = self
        //3 返回cell
        return cell

    }
}
//遵守协议，实现方法
extension CZEmoticoInputView:CZEmoticonCellDelegate{
    /// 选中的表情回调
    ///
    /// - Parameters:
    ///   - cell: 分页Cell
    ///   - em: 选中的表情 删除键为nil
    func emoticonCellDidSelectedEmoticon(cell: CZEmoticonCell, em: CZEmoticon?) {
        //执行闭包 回调选中的表情
        selectedEmoticonCallBack?(em)
        //添加最近使用的表情
        
        guard let em = em else {
            return
        }
        //如果当前的collectionview就是最近分组  不添加最近使用的表情
        let indexPath = collectionView.indexPathsForVisibleItems[0]
        if indexPath.section == 0 {
            return
        }
        
        CZEmoticonManager.shared.recentEmoticon(em: em)
        //刷新第0组
        var indexSet = IndexSet()
        indexSet.insert(0)
        collectionView .reloadSections(indexSet)
    }
}
extension CZEmoticoInputView{
    func setUPUI() {
        let bottomView = UIView(frame: CGRect(x: 0, y: self.frame.size.height-40, width: self.frame.size.width, height: 40))
        self.addSubview(bottomView)
        
        let collect = UICollectionView(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height-40))
        collect.backgroundColor = UIColor.orange
        self.addSubview(collect)
        
    }
}
